/*
 * jsmap 0.5
 * http://code.google.com/p/jsmap
 *
 * Copyright (c) 2011 CMS XLBS
 *
 * Licensed under Apache License
 * http://www.apache.org/licenses/
 *
 */
(function( $ ){

	/**
	 * return the jquery object (or the result returned from an executable-method call)
	 */
	$.fn.jsmap = function(options) {
		var args = Array.prototype.slice.call(arguments,1) , result = this;

		if (typeof options == 'string') { // call method $(...).jslist("showMore") or call property $(...).jslist("data")
			this.each(function() {
				var current_instance = $.data(this, "_jsmap_instance");
				// call the method if the target is a function,otherwise return the target
				var returnValue = (current_instance && $.isFunction(current_instance[options])) ? current_instance[options].apply(current_instance, args) : current_instance;
				(options.indexOf("get") != 0 ) || (result = returnValue); 
			});
		}
		else {
			var _options = options ? $.extend({}, options) : {};
			_options.plugins = $.isArray(_options.plugins) ? _options.plugins : $.jsmap.defaults.plugins.slice();
			_options.plugins.unshift("core");

			this.each(function() { // dom element iterator
				var instance_options = $.extend(true, {}, $.jsmap.defaults, _options),// extend global default options with call arguments
				    current_instance = $.data(this, "_jsmap_instance"),
					$this = $(this); // dom element reference => jquery object reference
				current_instance || (current_instance = new $.jsmap._instance($this, instance_options)); 
				$.data(this, "_jsmap_instance", current_instance);
				// init all specfied plugins for this instance
				$.each(current_instance.get_options().plugins, 
						function (i, val) {
							$.extend(true,current_instance.data,(instance_options[val] ? instance_options[val] : {})); 
						});
				$.each(current_instance.get_options().plugins, 
						function (i, val) { 
							if($.jsmap._plugins[val]) { 
								$.jsmap._plugins[val]._init.apply(current_instance); 
							}
						});
			});
		}
		
		return result;
	};

	// jsmap global repository
	$.jsmap = {
		defaults : {
			plugins : []
		},
		_instance : function (container, options) { //the container is a jquery object (dom element wrappered)
			this.init = $.noop;
			this.destroy = $.noop;
			this.data = { }; // merged plugin options
			this.get_options	= function () { return $.extend(true, {}, options); }; // return options copy
			this.get_container	= function () { return container; };
		},
		_fn : {
			//can be accessed by this.xxx within instance execution context
			}, 
		_plugins : {
			//plugins repository,to access by plugin-name:_plugins["core"]
			},
		plugin : function (pluginName, pluginBody) {
			pluginBody = $.extend(
				{
					_init		: $.noop, 
					_destroy	: $.noop,
					_fn			: {}
				}, pluginBody);
			$.jsmap._plugins[pluginName] = pluginBody;
			$.jsmap.defaults[pluginName] = pluginBody.defaults;
			$.each(pluginBody._fn, function (fnName, fnBody) {
				$.jsmap._fn[fnName] = function () {
					return fnBody.apply(this, arguments);  //Here,"this" refer to the jsmap instance
				};
				$.jsmap._fn[fnName]._pluginName = pluginName;
			});
		}
	};
	
	$.jsmap._fn = $.jsmap._instance.prototype = {};
	
})( jQuery );

(function ($) {
	$.jsmap.plugin("core",{
		_init: function() {
			if (this.data.width > 0) {
			}
			this.totalCount = 0;
			this.markers = [];
			this.markerStatusCounts = {"draft":0,
										"assigned":0,
										"in_process":0,
										"completed":0};
			this.markerIcons = {"draft":"/images/map/pin-black.png",
								"assigned":"/images/map/pin-red.png",
								"in_process":"/images/map/pin-yellow.png",
								"completed":"/images/map/pin-blue.png"};
			this.infoWindow = new sogou.maps.InfoWindow({
			});
			
			var options = {
				'zoom' : this.data.zoom,
				'center' : new sogou.maps.Point(this.data.center.x, this.data.center.y),
				'mapTypeId' : this.data.mapTypeId
			};
			var map = new sogou.maps.Map(this.get_container().get()[0],options);
			map.setZoom(options.zoom+1);
			this.map = map;
		},
		defaults: {
			zoom:11,
			mapTypeId:sogou.maps.MapTypeId.ROADMAP,
			data:function() {return [];},
			info:function() {;}
		},
		_fn: { 
			refresh : function() {
				if (this.data.dataFunc == null) {
					return;
				}
				
				var data = this.data.dataFunc.apply(this);
				var _this = this;
				$.each(data,function(i,item){
					_this.makeMarker(item);
				});
				this.totalCount += data.length;
				
				this.get_container().triggerHandler(new $.Event("list_retrieved.jsmap"), {data:data});
		    },
		    makeMarker : function(item) {
				var counter = this.markerStatusCounts[item.status];
				if (counter != undefined) {
					 this.markerStatusCounts[item.status] = ++counter;
				}
				
				var marker;
				if (item.longitude != null && item.latitude != null) {
					var options = {
							position : new sogou.maps.Point(item.longitude, item.latitude),
							map : this.map,
							title : this.data.markerTitlePrefix + item.name + "(实际坐标)"
						};
					
					if (this.markerIcons[item.status] != null) {
						options = $.extend(options, {icon: this.markerIcons[item.status]});
					}
					
					marker = new sogou.maps.Marker( options );
				}
				else if (item.planLongitude != null && item.planLatitude != null) {
					var options = {
							position : new sogou.maps.Point(item.planLongitude, item.planLatitude),
							map : this.map,
							title : this.data.markerTitlePrefix + item.name + "(预定坐标)"
						};
					
					if (this.markerIcons[item.status] != null) {
						options = $.extend(options, {icon: this.markerIcons[item.status]});
					}
					
					marker = new sogou.maps.Marker( options );
				}
				
				if (marker != null) {
					marker.data = item;

					var _this = this;
					sogou.maps.event.addListener(marker, "click", function(e) {
						_this.infoWindow.setContent(_this.data.infoFunc(item));
						_this.infoWindow.open(_this.map, this);
					});

					this.markers.push(marker);
					this.map.setCenter(marker.options.position);
				}
			},
		    showInfo : function(id) { 
	    		$(this.markers).each(function(i,item) {
	    			if (item.data.id == id) {
	    				this.infoWindow.setContent(this.data.infoFunc(item.data));
						this.infoWindow.open(this.map, item);
	    			}
	    		});
		    },
		    addMore :function (data) {
		    	$(data,function(i,item){
					this.makeMarker(item);
				});
		    	
		    	this.totalCount += data.length;
		    },
		    clear : function() { 
		    	$(this.markers).each(function(i, marker) {
					marker.setMap(null);
					delete marker;
				});

				this.markers = [];
				this.totalCount = 0;

				this.get_container().triggerHandler(new $.Event("clear_all.jsmap"));
		    }
		}
	});
})( jQuery );

(function ($) {
	$.jsmap.plugin("toolbar",{
		_init: function() {
			$("<div class='btn-group' style='position:absolute;z-index:1000;right:0;top:0;'>"+
				"<a id='draftCountBtn' href='javascript:;' class='btn' ><img src='/images/map/pin-black.s.png'></img>草稿<small id='draftCount'></small></a>"+
				"<a id='assignedCountBtn' href='javascript:;' class='btn' ><img src='/images/map/pin-red.s.png'></img>已指派<small id='assignedCount'></small></a>"+
				"<a id='inProcessCountBtn' href='javascript:;' class='btn' ><img src='/images/map/pin-yellow.s.png'></img>处理中<small id='inProcessCount'></small></a>"+
				"<a id='completedCountBtn' href='javascript:;' class='btn' ><img src='/images/map/pin-blue.s.png'></img>已完成<small id='completedCount'></small></a>"+
				"<a id='allCountBtn' href='javascript:;' class='btn' ><img src='/images/map/pin-all.s.png'></img>显示所有<small id='allCount'></small></a>"+
			"</div>")
			.delegate("#draftCountBtn","click",$.proxy(function() {this.showDraft();},this))
			.delegate("#assignedCountBtn","click",$.proxy(function() {this.showAssigned();},this))
			.delegate("#inProcessCountBtn","click",$.proxy(function() {this.showInProgress();},this))
			.delegate("#completedCountBtn","click",$.proxy(function() {this.showCompleted();},this))
			.delegate("#allCountBtn","click",$.proxy(function() {this.showAll();},this))
			.appendTo($(this.map.getContainer()));
			 
			this.get_container().bind("list_retrieved.jsmap", $.proxy(function() {
				this.get_container().find("#draftCount").html("("+this.markerStatusCounts["draft"]+")");
				this.get_container().find("#assignedCount").html("("+this.markerStatusCounts["assigned"]+")");
				this.get_container().find("#inProcessCount").html("("+this.markerStatusCounts["in_process"]+")");
				this.get_container().find("#completedCount").html("("+this.markerStatusCounts["completed"]+")");
				this.get_container().find("#allCount").html("("+this.totalCount+")");
			},this));
		},
		defaults: {
		},
		_fn: { 
			 
			showDraft:function() {
				var _this = this;
				$(this.markers).each(function() {
					this.setVisible((this.data.status == "draft"));
					if (this.data.status == "draft") {
						_this.map.setCenter(this.options.position);
					}
				});
			},
			showInProgress:function () {
				var _this = this;
				$(this.markers).each(function() {
					this.setVisible((this.data.status == "in_process"));
					if (this.data.status == "in_process") {
						_this.map.setCenter(this.options.position);
					}
				});
			},
			showAssigned:function() {
				var _this = this;
				$(this.markers).each(function() {
					this.setVisible((this.data.status == "assigned"));
					if (this.data.status == "assigned") {
						_this.map.setCenter(this.options.position);
					}
				});
			},
			showCompleted:function() {
				var _this = this;
				$(this.markers).each(function() {
					this.setVisible((this.data.status == "completed"));
					if (this.data.status == "completed") {
						_this.map.setCenter(this.options.position);
					}
				});
			},
			showAll:function() {
				var _this = this;
				$(this.markers).each(function() {
					this.setVisible(true);
//					_this.map.setCenter(this.postion);
				});
			} 
		}
	});
})( jQuery );

